package com.njitt.bysj.controller;

import com.alibaba.excel.EasyExcel;
import com.njitt.bysj.base.BaseController;
import com.njitt.bysj.base.ResultInfo;
import com.njitt.bysj.mapper.BomBeanMapper;
import com.njitt.bysj.model.BomModel;

import com.njitt.bysj.srevice.ProjectDesignService;
import com.njitt.bysj.srevice.ProjectService;
import com.njitt.bysj.srevice.PurchaseService;
import com.njitt.bysj.srevice.SaleService;
import com.njitt.bysj.utils.AssertUtil;
import com.njitt.bysj.utils.ExcelListener;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @description:
 * @author: wyj
 * @time: 2022/4/8 23:02
 */
@Controller
@RequestMapping("file")
public class FileController extends BaseController {

    @Resource
    private SaleService saleService;
    @Resource
    private ProjectDesignService designService;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private ProjectService projectService;

    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("AlibabaTransact ionMustHaveRollback")
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> uploadFile(MultipartFile file, Integer id) {
        Map<String, Object> map = new HashMap<>();
        String originalFileName = file.getOriginalFilename();

        String realPath = "E:/ideaworkspace/temp";
        File targetFile = new File(realPath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 删除文件
        String lastName = saleService.fileName(id);
        if (StringUtils.isNotBlank(lastName)) {
            File deleteFile = new File(realPath + File.separator + lastName);
            if (deleteFile.exists()) {
                deleteFile.delete();
            }
        }
        String fileNewName = UUID.randomUUID().toString().replace("-", "") + originalFileName;
        String fileName = realPath + File.separator + fileNewName;
        System.out.println(fileName);
        try {
            file.transferTo(new File(fileName));
            saleService.updateDescription(id, fileNewName);
            map.put("code", 0);
            map.put("msg", "success");
        } catch (IOException exception) {
            map.put("code", 0);
            map.put("msg", "error");
        }
        return map;
    }

    @RequestMapping("downloadFile")
    public ResponseEntity<byte[]> downloadFile(Integer id) {
        System.out.println(id);
        String path = "E:/ideaworkspace/temp";
        AssertUtil.isTrue(id == null, "下载失败");
        String fileName = saleService.queryFileNameById(id);
        AssertUtil.isTrue(StringUtils.isBlank(fileName), "下载失败3");
        String realPath = path + File.separator + fileName;
        System.out.println(realPath);
        File file = new File(realPath);
        if (!file.exists()) {
            return null;
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment", fileName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);

        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "contract", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("AlibabaTransact ionMustHaveRollback")
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> contract(MultipartFile file, Integer id) {
        String originalFileName = file.getOriginalFilename();
        Map<String, Object> map = new HashMap<>(16);
        String realPath = "E:/ideaworkspace/temp/hetong";
        File targetFile = new File(realPath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String fileNewName = UUID.randomUUID().toString().replace("-", "") + originalFileName;
        String fileName = realPath + File.separator + fileNewName;
        System.out.println(fileName);
        try {
            file.transferTo(new File(fileName));
            saleService.updateContract(id, fileNewName);
            map.put("code", 0);
            map.put("msg", "success");
        } catch (IOException exception) {
            map.put("code", 0);
            map.put("msg", "error");
        }
        return map;
    }



    @RequestMapping("importExcel")
    @ResponseBody
    @SuppressWarnings("AlibabaTransact ionMustHaveRollback")
    @Transactional(propagation = Propagation.REQUIRED)
    public ResultInfo importExcel(@RequestParam(value = "file") MultipartFile file, Integer id, Integer projectId) throws IOException {
        EasyExcel.read(file.getInputStream(), BomModel.class, new ExcelListener(projectService)).sheet().doRead();
        designService.updateProjectDesignStatusByBom(id);
        purchaseService.addProjectToSelectPurchaser(projectId);
        return success("success");
    }
}
